const myAxios = function (config) {
  const { method, url, params, data } = config;

  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();

    if (method.toUpperCase() === 'GET') {
      const str = getParams(params);
      console.log(str);
      xhr.open('GET', params ? url + '?' + str : url);
      xhr.send();
    } else {
      xhr.open('POST', url);
      
      const flag = Object.prototype.toString.call(data) === '[object Object]'
      xhr.setRequestHeader('Content-Type', flag ? 'application/json':'application/x-www-form-urlencoded');
      xhr.send(flag? JSON.stringify(data) : data);
    }

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status >= 200 && xhr.status < 300) {
          resolve(JSON.parse(xhr.responseText));
        } else {
          reject('错误,状态为400');
        }
      }
    };
  });
};

function getParams(obj) {
  const arr = [];
  for (let key in obj) {
    const res = key + '=' + obj[key];
    arr.push(res);
  }
  return arr.join('&');
}
